#include "ffz/raft/raft-timer.h"
#define DEBUG DEBUG_NONE
#include "ffz/debug.h"
#include "random.h"
#include <stdio.h>
/**
 * clockUnit will be used in refreshCandidateClock()
 * each time call refreshCandidateClock(),
 * the candidateClockCounter += clockUnit
 * */
static uint16_t clockUnit = 1;

static uint16_t clockCounters[3] = {0};

static uint16_t triggerClocks[3] = {5, LEADER_BEATS_SECONDS, CANDIDATE_PERIODIC_REQUEST};

uint16_t getResetCandidateTime()
{
    return random_rand() % CANDIDATE_RANDOM_SECONDS + CANDIDATE_RANDOM_SECONDS;
}

void initCandidateClockUnit(uint16_t val)
{
    clockUnit = val;
    resetClockCount(1);
}

uint16_t refreshCandidateClock(uint8_t index)
{
    clockCounters[index] += clockUnit;
    return clockCounters[index];
}

void setTriggerClockAndClearCount(uint16_t interval, uint8_t index)
{
    clockCounters[index] %= triggerClocks[index];
    if (interval != 0)
        triggerClocks[index] = interval;
}

void resetClockCount(uint8_t index)
{
    clockCounters[index] = 0;
    if (index == COUNTER_INDEX_CANDIDATE)
    {
        uint16_t interval = getResetCandidateTime();
        setTriggerClockAndClearCount(interval, index);
    }
    else
    {
        setTriggerClockAndClearCount(0, index);
    }
}

uint16_t getTriggerClock(uint8_t index)
{
    return triggerClocks[index];
}